package kamkor.webtools.url

/**
 * Url Regex Patterns for
 * 
 * Allowed characters in url are specified in RFC 1738 document.
 * 
 * Urls must not have unsafe space in path or filename. Urls with spaces in path
 * won't be properly matched. 
 * 
 * @author kamkor
 *
 */
object UrlPatterns extends Enumeration {	
	/** Allowed characters in url */
	private val chars = """\w\d$!_'\-()+*,&@:;=?"""
		
	/** Characters that are allowed, but are unsafe and may be interpreted wrong. Dot included */
	private val unsafeChars = """"" <>#%{}|\^~\[\]`\."""
		
	/** space " [ ] < > excluded. Dot included */
	private val unsafeCharsLimited = """#%{}|\^~`\."""
		
	/** Safe allowed characters class for regex */
	private val charsClass = """["""+ chars +"""]"""
	
	/** Unsafe + safe allowed characters class for regex */
	private val unsafeCharsClass = """["""+ chars + unsafeChars +"""]"""
	
	/** Unsafe limited + safe characters class for regex. Works with tags [img], <img src=" etc */
	private val unsafeCharsLimitedClass = """["""+ chars + unsafeCharsLimited +"""]"""	
	
	/** 
	 * Pattern that will only match host, with "/" at the end excluded. 
	 * For example http://www.driftforum.pl from http://www.driftforum.pl/test/test will be matched 
	 * */
	val hostPattern = 
		 	"""(https?://){1}""" + // http:// once. => http:// 
			"""(www\.)?""" + // www. once or not at all. => http://www. or http://
			"""("""+ charsClass +"""+\.)+""" + // something. once or not at all. => http://something. or http://www.something.something2.	
		    """[\w]+""" // com, pl etc. => http://www.something.pl				
			
	/** 
	 * Will match urls that are just hosts and hosts+path. File excluded
	 * http://www.driftforum.pl/ => http://www.driftforum.pl/ will be matched
	 * http://www.driftforum.pl/p1/p2/p3/gfgd.zip => http://www.driftforum.pl/p1/p2/p3/ 
	 * 
	 * Urls can't have [ ] < > space " signs
	 * */
	val hostAndPathPattern =			
			hostPattern + 
			"""(/"""+ unsafeCharsLimitedClass +"""+/""" + // /path/		 // replaceAllUrlPathIncludedTest fails if unsafeCharsClass is used here
			"""("""+ unsafeCharsLimitedClass +"""+/)*|/)?""" // /p/p1/p2p/ etc or /
			
	
	/** 
	 * Will match the same as hostAndPathPattern and also file
	 * http://www.driftforum.pl/p1/p2/p3/gfgd.zip => http://www.driftforum.pl/p1/p2/p3/gfgd.zip	 
	 * 
	 * Urls can't have [ ] < > space " signs
	 */
	val hostAndPathAndFilePattern = hostAndPathPattern + unsafeCharsLimitedClass +"""*"""
	
	val hostAndPathAndFileUnsafePattern =
			hostPattern + 
			"""(/"""+ unsafeCharsClass +"""+/"""+
			"""("""+ unsafeCharsClass +"""+/)*|/)?"""+
			unsafeCharsClass +"""*"""
}